<%@ page contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.TableData"%>
<%@page import="dbexp.model.Table"%>
<%@page import="dbexp.model.Column"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="dbexp.connection.DbConnection"%>
<%@page import="org.json.JSONArray"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONException"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
String rowsData = request.getParameter("data");
boolean brak = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
TableData t = new TableData(name,schema);
Table oldTable = null;
if(!brak){
	List<Column> oldColumns = null;
	int ACTION = DbConnection.INSERT_RECORD;
	if( (oldTable = DbMetaData.getTable(u,name,schema)).requiredFieldIsNotNull() ){
		oldColumns = oldTable.getColumns();
		t.setColumns(oldColumns);
	}
	JSONArray data = null;
	try{
	data = new JSONArray(rowsData);
	}catch (JSONException e) {
		try {
			data = new JSONArray("["+rowsData+"]");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	for(int row=0;row<data.length();row++){
		JSONObject o = data.getJSONObject(row);
		List<Object> oneRow = new ArrayList<Object>();
			for (int c = 0; c< oldColumns.size(); c++) {//dla wszystkich kolumn z tabeli
				oneRow.add(o.get(oldColumns.get(c).getName().toLowerCase()));
			}
		t.addData(oneRow);
	}
	DbMetaData.operateObject(u,t,ACTION);
	List<Column> columns = t.getColumns();
	JSONArray array = new JSONArray();
	for(int i=0;i<columns.size();i++){
		Column c = columns.get(i);
		array.put(i, new JSONObject().put("name",c.getName()).put("dataType",c.getDataType()).put("size",c.getSize()).put("scale",c.getScale()).put("nullable",c.isNullable()).put("default",c.getDefault()) );
	}
	
	JSONObject my_out = new JSONObject().put("success", true).put("data",array);
	
	out.clearBuffer();%><%=my_out %>
<%}else{%>
<%=new JSONObject().put("success", false) %>
<%}%>